<?php
namespace Common\Model;

class PlanCostLimitModel extends Model {
    protected $tableName = 'acl';

    const TYPE  = 'cost_limit';
    const OTYPE = 'plan';

    /**
     * save2
     *
     * $d 是从表单传递过来的，其数据格式如下：
     * $d = [
     *      468 => 'A_1',
     *      .|...   | |
     *       |      | +-> tag编号
     *       |      +-> 分类标识符
     *       +-> 计划编号
     * ]
     *
     * @param mixed $d
     * @return void
     */
    public function save2($d) {
        /**
         * 先删除所有cost_limit数据
         * 后面再重建
         */
        $this->delAll();

        if (empty($d)) {
            return true;
        }

        /**
         * $dao的数据以 分类标识符为下标，值为计划编号数组
         */
        $dao = [];

        foreach ($d as $_planId => $_class) {
            if (empty($_class)) {
                continue;
            }

            $dao[$_class][] = $_planId;
        }

        if (empty($dao)) {
            return true;
        }

        $planModel = D2('Plan');

        foreach ($dao as $k => $_planIds) {
            $_tmp = explode('_', $k);

            if (count($_tmp) < 2) {
                continue;
            }

            list($_class, $_tagId) = $_tmp;

            if (empty($_class) || empty($_tagId)) {
                continue;
            }

            /**
             * 获取tag_id相同的所有投放中的计划编号
             */
            $_planExpr = [
                'tag_id' => $_tagId,
                'status' => 1,  //1表示投放中
            ];

            if (!$_planRecords = $planModel->field('planid AS plan_id')->where($_planExpr)->select()) {
                continue;
            }

            $_planIds2 = array_map(function($row) { return $row['plan_id']; }, $_planRecords);
            $_ids      = array_values(array_diff($_planIds2, $_planIds));
            $_data     = [
                'class'  => $_class,
                'tag_id' => $_tagId,
                'ids'    => $_ids,
            ];

            foreach ($_planIds as $_planId) {
                $_dao = [
                    'type'    => self::TYPE,
                    'otype'   => self::OTYPE,
                    'oid2'    => $_planId,
                    'include' => 0,
                    'data'    => json_encode($_data),
                ];

                if (!$this->add($_dao)) {
                    throw new ThinkException('保存计费限制出错');
                }
            }
        }

        cacheApi('planCostLimit', 1);

        return true;
    }

    public function getByPlanId($id) {
        $id = (int)$id;
        $expr = array(
            'type'  => self::TYPE,
            'otype' => self::OTYPE,
            'oid2'  => $id,
        );

        if ($r = $this->where($expr)->find()) {
            $r['data'] = explode(',', $r['data']);
        }

        return $r;
    }

    /**
     * delAll
     * 删除所有costLimit数据
     *
     * @return void
     */
    public function delAll() {
        $expr = [
            'type'  => self::TYPE,
            'otype' => self::OTYPE,
        ];

        return $this->where($expr)->delete();
    }

}
